package services

import (
	"dog-blog/app/post/models"
	"dog-blog/base/storage"

	"github.com/russross/blackfriday"
)

// Retrieval 检索本地文章
func Retrieval() int {
	storage.LoadPost()
	return len(storage.GetArticleMap())
}

// ArticleTotal 获取文章总数
func ArticleTotal() (total int) {
	total = len(storage.GetArticleMap())
	return total
}

// GetPage 获取分页数据
func GetPage(pageNum int, pageLimit int, typ string, fd string) models.ArticlePage {
	ids := storage.FilterArticleIds(typ, fd)
	return Paginate(ids, pageNum, pageLimit)
}

// Paginate 对数据进行分页
func Paginate(ids []string, pageNum int, pageLimit int) models.ArticlePage {
	pageNum = pageNum - 1
	stIdx := pageLimit * pageNum
	edIdx := stIdx + pageLimit

	hasNextPage := true
	size := len(ids)

	if edIdx > size {
		edIdx = size
		hasNextPage = false
	}

	ids = ids[stIdx:edIdx]

	rows := []models.Article{}

	for _, id := range ids {
		rows = append(rows, storage.GetArticleByID(id))
	}

	page := models.ArticlePage{}
	page.PrevPage = (pageNum)
	page.NextPage = (pageNum + 2)
	page.HasPrevPage = false
	page.HasNextPage = hasNextPage
	page.Rows = rows

	return page
}

// FindByID 通过文章id查找文章
func FindByID(id string) (models.Article, bool) {
	article := storage.GetArticleByID(id)
	if article.IsEmpty() {
		return article, false
	}

	// TODO ..
	if article.Content == "" {
		content := string(blackfriday.MarkdownCommon(article.ContentByte))
		article.Content = content
	}
	return article, true
}

// GetRecommend 获取推荐文章
func GetRecommend() []models.Article {
	articleList := storage.GetArticleMap()
	result := []models.Article{}
	for _, v := range articleList {
		result = append(result, v)
	}
	return result
}

// GetGuesslike 获取猜你喜欢文章
func GetGuesslike() []models.Article {
	articleList := storage.GetArticleMap()
	result := []models.Article{}
	for _, v := range articleList {
		result = append(result, v)
	}
	return result
}
